"""
AI分析结果相关的数据模式
"""
from dataclasses import dataclass, field
from typing import Optional, List, Any, Dict
from datetime import datetime
from enum import Enum


class AIResultType(str, Enum):
    """AI结果类型枚举"""
    BEHAVIOR_ANALYSIS = "behavior_analysis"
    CROWD_DENSITY = "crowd_density"
    WASTE_DETECTION = "waste_detection"
    CLEANLINESS_ASSESSMENT = "cleanliness_assessment"
    TEACHING_QUALITY = "teaching_quality"
    CLASSROOM_QUALITY = "classroom_quality"
    CONFLICT_DETECTION = "conflict_detection"
    POSE_DETECTION = "pose_detection"
    TRAJECTORY_ANALYSIS = "trajectory_analysis"
    LIGHTING_DETECTION = "lighting_detection"
    ENERGY_ANALYSIS = "energy_analysis"


@dataclass
class AIResultBase:
    """AI分析结果基础模式"""
    camera_id: int
    algorithm_name: str
    result_type: AIResultType
    result_data: Dict[str, Any]
    confidence: Optional[float] = None
    bounding_boxes: Optional[List[Dict[str, Any]]] = None
    timestamp: Optional[datetime] = None
    extra_data: Optional[Dict[str, Any]] = None
    
    # 实时处理相关字段
    frame_timestamp: Optional[datetime] = None
    frame_id: Optional[str] = None
    stream_info: Optional[Dict[str, Any]] = None
    is_real_time: bool = False
    batch_id: Optional[str] = None
    worker_id: Optional[str] = None
    gpu_id: Optional[int] = None
    frame_size: Optional[Dict[str, int]] = None
    alert_triggered: bool = False
    
    def __post_init__(self):
        if self.timestamp is None:
            self.timestamp = datetime.now()
    
    def to_dict(self) -> Dict[str, Any]:
        return {
            'camera_id': self.camera_id,
            'algorithm_name': self.algorithm_name,
            'result_type': self.result_type.value,
            'result_data': self.result_data,
            'confidence': self.confidence,
            'bounding_boxes': self.bounding_boxes,
            'timestamp': self.timestamp.isoformat() if self.timestamp else None,
            'extra_data': self.extra_data,
            'frame_timestamp': self.frame_timestamp.isoformat() if self.frame_timestamp else None,
            'frame_id': self.frame_id,
            'stream_info': self.stream_info,
            'is_real_time': self.is_real_time,
            'batch_id': self.batch_id,
            'worker_id': self.worker_id,
            'gpu_id': self.gpu_id,
            'frame_size': self.frame_size,
            'alert_triggered': self.alert_triggered
        }


@dataclass
class AIResultCreate(AIResultBase):
    """创建AI分析结果模式"""
    task_id: Optional[int] = None


@dataclass
class AIResultUpdate:
    """更新AI分析结果模式"""
    result_data: Optional[Dict[str, Any]] = None
    confidence: Optional[float] = None
    bounding_boxes: Optional[List[Dict[str, Any]]] = None
    extra_data: Optional[Dict[str, Any]] = None
    alert_triggered: Optional[bool] = None
    
    def to_dict(self) -> Dict[str, Any]:
        return {
            'result_data': self.result_data,
            'confidence': self.confidence,
            'bounding_boxes': self.bounding_boxes,
            'extra_data': self.extra_data,
            'alert_triggered': self.alert_triggered
        }


@dataclass
class AIResultResponse(AIResultBase):
    """AI分析结果响应模式"""
    id: Optional[int] = None
    task_id: Optional[int] = None
    processing_latency: Optional[float] = None
    processed_at: Optional[datetime] = None
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None
    
    def to_dict(self) -> Dict[str, Any]:
        result = super().to_dict()
        result.update({
            'id': self.id,
            'task_id': self.task_id,
            'processing_latency': self.processing_latency,
            'processed_at': self.processed_at.isoformat() if self.processed_at else None,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        })
        return result


@dataclass
class AIResultListResponse:
    """AI分析结果列表响应模式"""
    items: List[AIResultResponse]
    total: int
    page: int
    size: int
    pages: int
    
    def to_dict(self) -> Dict[str, Any]:
        return {
            'items': [item.to_dict() for item in self.items],
            'total': self.total,
            'page': self.page,
            'size': self.size,
            'pages': self.pages
        }


@dataclass
class AIResultFilters:
    """AI分析结果筛选条件"""
    camera_id: Optional[int] = None
    algorithm_name: Optional[str] = None
    result_type: Optional[AIResultType] = None
    is_real_time: Optional[bool] = None
    alert_triggered: Optional[bool] = None
    start_time: Optional[datetime] = None
    end_time: Optional[datetime] = None
    page: int = 1
    size: int = 10
    
    def to_dict(self) -> Dict[str, Any]:
        return {
            'camera_id': self.camera_id,
            'algorithm_name': self.algorithm_name,
            'result_type': self.result_type.value if self.result_type else None,
            'is_real_time': self.is_real_time,
            'alert_triggered': self.alert_triggered,
            'start_time': self.start_time.isoformat() if self.start_time else None,
            'end_time': self.end_time.isoformat() if self.end_time else None,
            'page': self.page,
            'size': self.size
        }


@dataclass
class RealTimeAIResult:
    """实时AI分析结果模式"""
    camera_id: int
    algorithm_name: str
    result_type: AIResultType
    result_data: Dict[str, Any]
    confidence: Optional[float] = None
    bounding_boxes: Optional[List[Dict[str, Any]]] = None
    frame_timestamp: Optional[datetime] = None
    frame_id: Optional[str] = None
    processing_latency: float = 0.0
    worker_id: Optional[str] = None
    gpu_id: Optional[int] = None
    alert_triggered: bool = False
    
    def __post_init__(self):
        if self.frame_timestamp is None:
            self.frame_timestamp = datetime.now()
    
    def to_dict(self) -> Dict[str, Any]:
        return {
            'camera_id': self.camera_id,
            'algorithm_name': self.algorithm_name,
            'result_type': self.result_type.value,
            'result_data': self.result_data,
            'confidence': self.confidence,
            'bounding_boxes': self.bounding_boxes,
            'frame_timestamp': self.frame_timestamp.isoformat() if self.frame_timestamp else None,
            'frame_id': self.frame_id,
            'processing_latency': self.processing_latency,
            'worker_id': self.worker_id,
            'gpu_id': self.gpu_id,
            'alert_triggered': self.alert_triggered
        }


@dataclass
class AIResultStatistics:
    """AI分析结果统计模式"""
    camera_id: int
    algorithm_name: str
    total_results: int = 0
    avg_confidence: Optional[float] = None
    avg_processing_latency: Optional[float] = None
    alert_count: int = 0
    last_result_time: Optional[datetime] = None
    success_rate: float = 0.0
    error_count: int = 0
    
    def to_dict(self) -> Dict[str, Any]:
        return {
            'camera_id': self.camera_id,
            'algorithm_name': self.algorithm_name,
            'total_results': self.total_results,
            'avg_confidence': self.avg_confidence,
            'avg_processing_latency': self.avg_processing_latency,
            'alert_count': self.alert_count,
            'last_result_time': self.last_result_time.isoformat() if self.last_result_time else None,
            'success_rate': self.success_rate,
            'error_count': self.error_count
        }


@dataclass
class BatchAIResultCreate:
    """批量创建AI分析结果模式"""
    results: List[AIResultCreate] = field(default_factory=list)
    batch_id: Optional[str] = None
    worker_id: Optional[str] = None
    
    def to_dict(self) -> Dict[str, Any]:
        return {
            'results': [result.to_dict() for result in self.results],
            'batch_id': self.batch_id,
            'worker_id': self.worker_id
        }